package org.andrewwinter.tescopricewar.tesco;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import com.google.gson.Gson;


public class TescoPriceChecker
{
    private final Gson GSON = new Gson();

    private LoginResult loginResult;

    public void login(final String email, final String password) throws Exception
    {
        final URL url = new URL("https://secure.techfortesco.com/groceryapi_b1/restservice.aspx?"
                + "COMMAND=LOGIN&"
                + "EMAIL=" + email + "&"
                + "PASSWORD=" + password + "&"
                + "DEVELOPERKEY=14X5SgZbMaYCMgqeZtU3&"
                + "APPLICATIONKEY=8C1302DBD0770A893440");

        final URLConnection conn = url.openConnection();
        final Reader reader = new InputStreamReader(conn.getInputStream());

        loginResult = GSON.fromJson(reader, LoginResult.class);

        reader.close();
    }

    public TescoSearchResult search(String itemDescription) throws Exception
    {
        itemDescription = URLEncoder.encode(itemDescription, "UTF-8");

        final URL url = new URL("http://www.techfortesco.com/groceryapi_b1/restservice.aspx?"
                + "COMMAND=PRODUCTSEARCH&"
                + "SESSIONKEY=" + loginResult.getSessionKey() + "&"
                + "SEARCHTEXT=" + itemDescription);

        URLConnection conn;
        Reader reader = null;

        boolean readSuccessfully = false;
        do
        {
            try
            {
                conn = url.openConnection();
                reader = new InputStreamReader(conn.getInputStream());
                readSuccessfully = true;
            }
            catch (IOException e)
            {
                Thread.sleep(500);
            }
        } while (readSuccessfully == false);

        final TescoSearchResult searchResult = GSON.fromJson(reader, TescoSearchResult.class);

        reader.close();

        return searchResult;
    }
}
